<template>
    <ul class="wrapper">
        <li
            v-for="item of letters"
            :key="item"
            :ref="item"
            @click="handleLetterClick"
            @touchstart.prevent="handleTouchStart"
            @touchmove="handleTouchMove"
            @touchend="handleTouchEnd"
        >
            {{item}}
        </li>
    </ul>
</template>

<script>
export default {
  name: 'CityAlphabet',
  data () {
    return {
      touchStatus: false,
      startY: 0
    }
  },
  props: {
    cities: Object
  },
  computed: {
    letters () {
      const letters = []
      for (let k in this.cities) {
        letters.push(k)
      }
      return letters
    }
  },
  methods: {
    handleLetterClick (e) {
      this.$emit('change', e.target.innerText)
    },
    handleTouchStart () {
      this.touchStatus = true
    },
    handleTouchMove (e) {
      if (this.touchStatus) {
        if (!this.timer) {
          this.timer = setTimeout(() => {
            const touchY = e.touches[0].clientY
            const index = Math.floor((touchY - this.startY - 79) / 20)
            const len = this.letters.length
            if (index >= 0 && index < len) {
              this.$emit('change', this.letters[index])
            }
            this.timer = null
          }, 16)
        }
      }
    },
    handleTouchEnd () {
      this.touchStatus = false
    }
  },
  updated () {
    this.startY = this.$refs['A'][0].offsetTop
  }
}
</script>

<style lang="stylus" scoped>
    @import "~styles/varibles.styl"
    .wrapper
        position absolute
        display flex
        flex-direction column
        justify-content center
        top 1.58rem
        right .2rem
        bottom 0
        li
            color $bgcolor
            margin .06rem
</style>
